import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { getStorageSync, setStorageSync } from '../utils/storage'
import dayjs from 'dayjs'

export const useTodosStore = defineStore('todos', () => {
  const today = dayjs().startOf('day')
  const selectedDay = ref(dayjs().startOf('day'))
  const isToday = computed(() => selectedDay.value.isSame(today, 'day'))

  const setDay = (date: string) => {
    selectedDay.value = dayjs(date).startOf('day')
  }

  // 全部待办事项列表
  const todoList = ref<TodoList>([])

  // 今日待办事项列表
  const todayTodos = computed(() => {
    // console.log(todoList.value)
    return todoList.value
      .filter(todo => {
        return todo.status === 'doing' && (todo.time === null || dayjs(todo.time).startOf('day').isSame(selectedDay.value, 'day'))
      })
  })

  const getTodoList = () => {
    try {
      const res: TodoList | null = getStorageSync('todoList')

      if (res) {
        todoList.value = res.map((todo) => ({
          ...todo,
          isSelected: false
        }))
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 按时间排序
  const sortTodoList = () => {
    todoList.value.sort((a, b) => {
      if (a.time === null) return -1
      if (b.time === null) return 1
      return a.time < b.time ? -1 : 1
    })
  }

  // 添加Todo
  const addTodo = (todo: Todo) => {
    todoList.value.push(todo)
    sortTodoList()
  }

  // 编辑Todo
  const editTodo = (todo: Todo) => {
    const index = todoList.value.findIndex(item => item.id === todo.id)
    if (index !== -1) {
      todoList.value[index] = todo
    }

    sortTodoList()
  }

  // 批量完成待办事项
  const completeTodos = (ids: string[]) => {
    todoList.value = todoList.value.map(todo => {
      if (ids.includes(todo.id)) {
        return {
          ...todo,
          status: 'done',
          doneTime: dayjs().unix()
        }
      }
      return todo
    })
  }

  // 批量删除待办事项
  const deleteTodos = (ids: string[]) => {
    todoList.value = todoList.value.filter(todo => !ids.includes(todo.id))
  }

  // 取消完成待办事项
  const cancelCompleteTodo = (id: string) => {
    todoList.value = todoList.value.map(todo => {
      if (todo.id === id) {
        return {
          ...todo,
          status: 'doing',
          doneDuring: null
        }
      }
      return todo
    })
  }

  const saveTodoList = () => {
    try {
      setStorageSync<TodoList>('todoList', todoList.value)
    } catch (error) {
      console.log(error)
    }
  }

  watch(() => todoList.value, saveTodoList, { deep: true })

  return {
    today,
    isToday,
    setDay,
    selectedDay,
    todoList,
    addTodo,
    editTodo,
    completeTodos,
    deleteTodos,
    cancelCompleteTodo,
    todayTodos,
    getTodoList
  }
})
